//
//  FZHomeAlbumCollectionViewCell.m
//  EnglishTalk
//
//  Created by CyonLeuPro on 15/6/30.
//  Copyright (c) 2015年 Feizhu Tech. All rights reserved.
//

#import "FZHomeAlbumCollectionViewCell.h"
#import "SRExpandSelectButton.h"
#import "FZHomeConstants.h"
#import "FZCircleProgressView.h"
#import "MCDownloadManager.h"
#import "FZMCCacheManager.h"

@interface FZHomeAlbumCollectionViewCell ()

@property (strong, nonatomic) UIButton *checkButton;
@property (strong, nonatomic) FZCircleProgressView *progressView;
@property (strong, nonatomic) UILabel *progressLabel;

@end

@implementation FZHomeAlbumCollectionViewCell

- (void)awakeFromNib {
    // Initialization code
    [super awakeFromNib];
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    
//    self.albumMarkLabel.backgroundColor = css.color_1;
//    self.albumMarkLabel.textColor = [UIColor whiteColor];
//    self.albumMarkLabel.font = css.fontOfH6;
//    self.albumMarkLabel.text = @" 专辑 ";
    self.iconImageView.clipsToBounds = YES;
    self.iconImageView.layer.cornerRadius = 4;
    
    
    self.checkButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.checkButton setContentVerticalAlignment:UIControlContentVerticalAlignmentTop];
    [self.checkButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    
    [self.checkButton setImage:[UIImage imageNamed:@"icon_delete"] forState:UIControlStateNormal];
//    [self.checkButton setImage:[UIImage imageNamed:@"common_btn_checkbox_sel"] forState:UIControlStateSelected];
    
    [self.contentView addSubview:self.checkButton];
    
    self.checkButtonHidden = YES;
    self.albumMarkHidden = YES;
    
    
    self.titleLabel.font = css.fontOfH3;
    self.titleLabel.textColor = css.color_1;
//    self.checkButton.backgroundColor = [UIColor redColor];
    
    [self.checkButton addTarget:self action:@selector(onClickButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.checkButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.equalTo(self.iconImageView.mas_trailing).offset(0);
        make.top.equalTo(self.iconImageView).offset(0);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(60);
    }];

    [self.contentView bringSubviewToFront:self.checkButton];
    
    self.progressView = [[FZCircleProgressView alloc] init];
    self.progressView.progressTintColor = css.color_7;
    self.progressView.progressRingWidth = 3;
    self.progressView.backgroundTintColor = css.color_4;
    self.progressView.progressTintColor = css.color_7;
    
    [self.contentView addSubview:self.progressView];
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.width.mas_equalTo(70);
//        make.height.mas_equalTo(70);
        make.leading.equalTo(self.contentView.mas_leading).offset(15);
        make.trailing.equalTo(self.contentView.mas_trailing).offset(-15);
        make.height.equalTo(self.progressView.mas_width);
        make.centerX.equalTo(self.contentView.mas_centerX);
        make.centerY.equalTo(self.contentView.mas_centerY);
    }];
    
    
    self.progressLabel = [[UILabel alloc] init];
    self.progressLabel.textColor = css.color_4;
    self.progressLabel.font = css.fontOfH5;
    self.progressLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.contentView addSubview:self.progressLabel];
    
    [self.progressLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(self.progressView.mas_leading).offset(5);
        make.trailing.equalTo(self.progressView.mas_trailing).offset(-5);
        make.height.mas_equalTo(30);
        make.centerY.equalTo(self.progressView.mas_centerY);
    }];
    
    self.progressView.hidden = YES;
    self.progressLabel.hidden = YES;
    WEAKSELF
    [self.progressView addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        [weakSelf onTapProgressView:nil];
    }];
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(onPrivewVideoInfoGesture:)];
//    [self.iconImageView addGestureRecognizer:tap];
}


- (void)setProgressHidden:(BOOL)progressHidden {
    _progressHidden = progressHidden;
    
    self.progressView.hidden = progressHidden;
    self.progressLabel.hidden = progressHidden;
    
}

- (void)updateCellInfo:(id)data {
    [super updateCellInfo:data];
    
    if (!data && ![data isKindOfClass:[FZHomeCourseModel class]]) {
        return;
    }
    self.bookModel = data;
    FZHomeCourseModel *item = (FZHomeCourseModel *)data;
    
//    self.checkButton.selected = item.isSelected;
//
    NSString *idString = [NSString stringWithFormat:@"%@", item.identifier];
    if ([idString isEqualToString:kHomeAddAlbumID]) {
            //添加按钮
//        self.iconImageView.image = [UIImage imageNamed:@"addAlbumButton"];
        [self.iconImageView fz_setImageWithURL:nil placeholder:[UIImage imageNamed:@"addAlbumButton"] completed:nil];

        self.progressView.hidden = YES;
        self.titleLabel.text = @"添加课本";
        self.titleLabel.hidden = NO;
    }else if ([idString isEqualToString:kHomeGuideAlbumID]) {
            //试用教材
//        self.iconImageView.image = [UIImage imageNamed:@"defaultTextbook"];
        [self.iconImageView fz_setImageWithURL:nil placeholder:[UIImage imageNamed:@"defaultTextbook"] completed:nil];
        
        self.progressView.hidden = YES;
        self.progressLabel.hidden = YES;
        self.titleLabel.text = @"试用教材";
        self.titleLabel.hidden = NO;
    }
     else {
        [self.iconImageView fz_setImageWithDefaultPlaceholderWithURL:[NSURL URLWithString:item.pic] placeholderSize:self.iconImageView.bounds.size];
        self.progressView.progress = item.dowloadProgress;
        self.progressView.hidden = NO;
        self.progressLabel.hidden = NO;
        self.titleLabel.text = nil;
        self.titleLabel.hidden = YES;

        if (item.downloadState == MCDownloadStateDownloading) {
            NSString *progressString = [NSString stringWithFormat:@"%d%%", (int)(item.dowloadProgress * 100)];
            self.progressLabel.text = progressString;
            
        } else if (item.downloadState == MCDownloadStateSuspened || item.downloadState == MCDownloadStateWillResume) {
            self.progressLabel.text = @"已暂停";
        } else if (item.downloadState == MCDownloadStateFailed) {
            self.progressLabel.text = @"下载失败";
        }
        else {
            self.progressView.hidden = YES;
            self.progressLabel.hidden = YES;
        }
        WEAKSELF
        item.successBlock = ^(NSURLRequest * _Nullable request, NSHTTPURLResponse * _Nullable response, NSURL * _Nonnull originURL, NSString * _Nonnull localFilePath) {
            weakSelf.progressLabel.text = @"下载完成";
            weakSelf.progressView.hidden = YES;
            weakSelf.progressLabel.hidden = YES;
        };
        
        item.progressBlock = ^(NSProgress * _Nonnull progress, MCDownloadReceipt * _Nonnull receipt) {
            weakSelf.progressView.hidden = NO;
            weakSelf.progressLabel.hidden = NO;
            if (receipt.state == MCDownloadStateDownloading) {
                weakSelf.progressView.progress = progress.fractionCompleted;
                NSString *progressString = [NSString stringWithFormat:@"%d%%", (int)(progress.fractionCompleted * 100)];
                weakSelf.progressLabel.text = progressString;
            } else if (item.downloadState == MCDownloadStateSuspened || item.downloadState == MCDownloadStateWillResume) {
                weakSelf.progressView.progress = progress.fractionCompleted;
                weakSelf.progressLabel.text = @"已暂停";
            }
        };
        
        item.failureBlock = ^(NSURLRequest * _Nullable request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
            weakSelf.progressView.hidden = NO;
            weakSelf.progressLabel.hidden = NO;
            weakSelf.progressLabel.text = @"下载失败";
        };
    }
    
}


- (void)setAlbumMarkHidden:(BOOL)albumMarkHidden {
    _albumMarkHidden = albumMarkHidden;
    
    self.albumMarkLabel.hidden = albumMarkHidden;
}

- (void)setCheckButtonHidden:(BOOL)checkButtonHidden {
    _checkButtonHidden = checkButtonHidden;
    
    self.checkButton.hidden = checkButtonHidden;
}

- (void)setCheckButtonStatus:(BOOL)isChecked {
    [self.checkButton setSelected:isChecked];
}

- (BOOL)checkButtonStatus {
    return self.checkButton.selected;
}

- (void)onDeleteButtonAction:(id)sender {
    if (self.delegate && [self.delegate respondsToSelector:@selector(albumCollectionViewCell:deleteItemIndexPath:)]) {
        [self.delegate albumCollectionViewCell:self deleteItemIndexPath:self.indexPath];
    }
}

- (IBAction)onClickButtonAction:(SRExpandSelectButton *)sender {
    
    if (sender.isSelected) {
        sender.selected = !sender.selected;
        if (self.delegate && [self.delegate respondsToSelector:@selector(albumCollectionViewCell:deselectItemIndexPath:)]) {
            [self.delegate albumCollectionViewCell:self deselectItemIndexPath:self.indexPath];
        }
    } else {
    
        sender.selected = !sender.selected;
        if (self.delegate && [self.delegate respondsToSelector:@selector(albumCollectionViewCell:didSelectItemIndexPath:)]) {
            [self.delegate albumCollectionViewCell:self didSelectItemIndexPath:self.indexPath];
        }
    }
}

-(void)onPrivewVideoInfoGesture:(UITapGestureRecognizer *)tapGesture {
    if (self.delegate && [self.delegate respondsToSelector:@selector(albumCollectionViewCell:previewVideoInfoItemIndexPath:)]) {
        [self.delegate albumCollectionViewCell:self previewVideoInfoItemIndexPath:self.indexPath];
    }
}

- (void)onTapProgressView:(id)sender {
    MCDownloadReceipt *receipt = [[MCDownloadManager defaultInstance] downloadReceiptForURL:self.bookModel.zip];
    if (receipt) {
        if (receipt.state == MCDownloadStateDownloading) {
            [[MCDownloadManager defaultInstance] suspendWithDownloadReceipt:receipt];
            [self updateProgressViewWithDownloadState:MCDownloadStateSuspened progress:self.bookModel.dowloadProgress];
        } else {
            [[FZMCCacheManager defaultManager] startDownloadBook:self.bookModel];
            [self updateProgressViewWithDownloadState:MCDownloadStateDownloading progress:self.bookModel.dowloadProgress];
        }
    }
}

- (void)updateProgressViewWithDownloadState:(MCDownloadState)downloadState progress:(CGFloat)downloadProgress {
    self.progressView.progress = downloadProgress;
    if (downloadState == MCDownloadStateDownloading) {
        NSString *progressString = [NSString stringWithFormat:@"%d/%%", (int)(downloadProgress * 100)];
        self.progressLabel.text = progressString;
        
    } else if (downloadState == MCDownloadStateSuspened || downloadState == MCDownloadStateWillResume) {
        self.progressLabel.text = @"已暂停";
    } else if (downloadState == MCDownloadStateFailed) {
        self.progressLabel.text = @"下载失败";
    }
}

@end
